package com.elinkway.infinitemovies.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.elinkway.infinitemovies.adapter.FavoriteGalleryAdapter;
import com.elinkway.infinitemovies.adapter.GalleryAdapter;
import com.elinkway.infinitemovies.adapter.HistoryGalleryAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.CollectionListBean;
import com.elinkway.infinitemovies.bean.Favorite;
import com.elinkway.infinitemovies.bean.JumpData;
import com.elinkway.infinitemovies.bean.LocalVideoEpisode;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bean.PlayRecordList;
import com.elinkway.infinitemovies.bean.UserMessageBean;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.RealDataApi;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.FavoriteDao;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.download.DownloadFolderJob;
import com.elinkway.infinitemovies.download.DownloadHelper;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.download.DownloadManager;
import com.elinkway.infinitemovies.download.DownloadObserver;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.UserMessageParser;
import com.elinkway.infinitemovies.http.requestInterface.RequestCommonInterface;
import com.elinkway.infinitemovies.http.requesttask.RequestAlbumInfoTask;
import com.elinkway.infinitemovies.http.requesttask.RequestGetFavoriteListTask;
import com.elinkway.infinitemovies.http.requesttask.RequestUserPlayRecordsTask;
import com.elinkway.infinitemovies.listener.OnItemListener;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.LoginDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.ui.activity.DownloadActivity;
import com.elinkway.infinitemovies.ui.activity.DownloadJobActivity;
import com.elinkway.infinitemovies.ui.activity.FavoriteActivity;
import com.elinkway.infinitemovies.ui.activity.LoginActivity;
import com.elinkway.infinitemovies.ui.activity.PlayHistoryActivity;
import com.elinkway.infinitemovies.ui.activity.SettingActivity;
import com.elinkway.infinitemovies.ui.activity.UserMessageActivity;
import com.elinkway.infinitemovies.ui.activity.VideoDetailActivity;
import com.elinkway.infinitemovies.ui.activity.commonwebview.CommonWebViewActivity;
import com.elinkway.infinitemovies.ui.activity.play.PlayActivitySelfOwn;
import com.elinkway.infinitemovies.utils.IdUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.UpdateManager;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.CircleImageView;
import com.elinkway.infinitemovies.view.PagerSlidingTabStrip;
import com.elinkway.infinitemovies.view.PublicLoadLayout;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaopeipei on 2016/5/30.
 */
public class MyFragment extends BaseFragment implements DownloadObserver,
        View.OnClickListener, RequestCommonInterface, OnItemListener {

    public static final String TAG = "MyFragment";
    private final String PREFIX = "file://";
    private static final int LIMIT = 20;	//每一页的数据数量
    private PublicLoadLayout root;
    RelativeLayout mLoginRelative;

    RelativeLayout mCheckUpgradeRelative;
    RelativeLayout mLawRelative;
    RelativeLayout mDownloadRelative;
    RelativeLayout mPlayHistoryRelative;
    RelativeLayout mFavoriteRelative;
    RelativeLayout mProductFeedBackRelative;
    RelativeLayout mSettingRelative;
    CircleImageView mHeadImageView;
    TextView mUnLoginHeadTextView;
    TextView mLoginHeadTextView;
    TextView mLoginTextViewDescription;
    private SharedPreferences mLoginSp;
    private UserMessageBean mUserMessage;
    private ImageView collectRedPop;
    private ImageView loginArrowIamge;
    private FavoriteDao favoriteDao;

    String headerIcon;
    String userName;
    String userSex;

    public final static String INFOIMAGEURL = "infoimageUrl";
    public final static String INFOGENDER = "infogender";
    public final static String INFONICKNAME = "infonickname";

    private PagerSlidingTabStrip mTabs;

    private RecyclerView mDownloadRecyclerView;
    private GalleryAdapter mDownloadAdapter;
    private DownloadManager mDownloadManager;
    private SparseArray<DownloadFolderJob> mDownloadData;
    private RecyclerView mHistoryRecyclerView;
    private HistoryGalleryAdapter mHistoryAdapter;
    private List<PlayRecord> playRecordList;
    private RecyclerView mFavoriteRecyclerView;
    private FavoriteGalleryAdapter mFavoriteAdapter;
    private List<Favorite> favoriteList;
    private Handler mHandler;
    private RequestGetFavoriteListTask mRequestGetFavoriteListTask;

    public MyFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        mLoginSp = getActivity().getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
        ScrollView myFragmentLayoutLl = (ScrollView) view.findViewById(R.id.sv_my_fragment);
        Rect frame = new Rect();
        mHandler = new Handler();
        favoriteDao = new FavoriteDao(getActivity());
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int actionBarHeight = getSupportActionBar().getHeight();
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        lp.setMargins(0, actionBarHeight, 0, 0);
        myFragmentLayoutLl.setLayoutParams(lp);

        initView(view);
        initData();

        headerIcon = mLoginSp.getString(INFOIMAGEURL, "");
        userName = mLoginSp.getString(INFONICKNAME, "");
        userSex = mLoginSp.getString(INFOGENDER, "");

        return view;
    }

    private void initView(View view) {
        loginArrowIamge = (ImageView)view.findViewById(R.id.iv_login_arrow) ;
        collectRedPop = (ImageView)view.findViewById(R.id.collect_redpop);
        mLoginRelative = (RelativeLayout) view.findViewById(R.id.click_to_login_rl);
        mLoginRelative.setOnClickListener(this);
        mCheckUpgradeRelative = (RelativeLayout) view.findViewById(R.id.menu_upgrade);
        mCheckUpgradeRelative.setOnClickListener(this);
        mLawRelative = (RelativeLayout) view.findViewById(R.id.menu_law);
        mLawRelative.setOnClickListener(this);
        mDownloadRelative = (RelativeLayout) view.findViewById(R.id.rl_download_manager);
        mDownloadRelative.setOnClickListener(this);
        mDownloadRecyclerView = (RecyclerView) view.findViewById(R.id.rv_download);
        mHistoryRecyclerView = (RecyclerView) view.findViewById(R.id.rv_history);
        mFavoriteRecyclerView = (RecyclerView) view.findViewById(R.id.rv_favorite);
        mPlayHistoryRelative = (RelativeLayout) view.findViewById(R.id.rl_play_history);
        mPlayHistoryRelative.setOnClickListener(this);
        mFavoriteRelative = (RelativeLayout) view.findViewById(R.id.menu_favourites);
        mFavoriteRelative.setOnClickListener(this);
        mProductFeedBackRelative = (RelativeLayout) view.findViewById(R.id.menu_feedback);
        mProductFeedBackRelative.setOnClickListener(this);
        mSettingRelative = (RelativeLayout) view.findViewById(R.id.menu_setting);
        mSettingRelative.setOnClickListener(this);
        mHeadImageView = (CircleImageView)view.findViewById(R.id.user_header_icon_iv);
        mUnLoginHeadTextView = (TextView)view.findViewById(R.id.tv_user_name_not_login);
        mLoginHeadTextView = (TextView)view.findViewById(R.id.tv_user_name_login);
        mLoginTextViewDescription = (TextView)view.findViewById(R.id.tv_login_description);
    }

    private void initData() {
        if (mDownloadRecyclerView != null) {
            mDownloadManager = MoviesApplication.getInstance().getDownloadManager();
            mDownloadData = mDownloadManager.getProvider().getFolderJobs();
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            mDownloadRecyclerView.setLayoutManager(linearLayoutManager);
            if (mDownloadData.size() > 0) {
                mDownloadRecyclerView.setVisibility(View.VISIBLE);
                //设置适配器
                mDownloadAdapter = new GalleryAdapter(getActivity(), mDownloadData);
                mDownloadRecyclerView.setAdapter(mDownloadAdapter);
                mDownloadAdapter.setOnItemClickListnener(this);
            } else {
                mDownloadRecyclerView.setVisibility(View.GONE);
            }
        }
        if (mHistoryRecyclerView != null) {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            mHistoryRecyclerView.setLayoutManager(linearLayoutManager);
            if (!TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                playRecordList = new PlayRecordDao(getActivity()).selectFromServer(20);
            } else {
                List<String> noPosterRecordList = new PlayRecordDao(getActivity()).getNoPosterAidList();
                if(noPosterRecordList != null && noPosterRecordList.size() > 0){
                    new RequestAlbumInfoTask(getActivity(), noPosterRecordList, "record").start();
                }
                playRecordList = new PlayRecordDao(getActivity()).getLocalAll();
            }
            if (playRecordList.size() > 0) {
                mHistoryRecyclerView.setVisibility(View.VISIBLE);
                //设置适配器
                mHistoryAdapter = new HistoryGalleryAdapter(getActivity(), playRecordList);
                mHistoryAdapter.setOnItemClickListnener(this);
                mHistoryRecyclerView.setAdapter(mHistoryAdapter);
            }
        }
        if (mFavoriteRecyclerView != null) {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            mFavoriteRecyclerView.setLayoutManager(linearLayoutManager);
            if(!"".equals(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                mRequestGetFavoriteListTask = new RequestGetFavoriteListTask(getActivity(), 0, LIMIT);
                mRequestGetFavoriteListTask.setRequestListener(this);
                mRequestGetFavoriteListTask.start();
            }else{
                List<String> noPosterFavoriteList = favoriteDao.getNoPosterAidList();
                if(noPosterFavoriteList != null && noPosterFavoriteList.size() > 0){
                    new RequestAlbumInfoTask(getActivity(), noPosterFavoriteList, "favorite").start();
                }
                favoriteList=favoriteDao.getAll();
                if (favoriteList.size() == 0) {
                } else {
                    mFavoriteRecyclerView.setVisibility(View.VISIBLE);
                    //设置适配器
                    mFavoriteAdapter = new FavoriteGalleryAdapter(getActivity(), favoriteList);
                    mFavoriteAdapter.setOnItemClickListnener(this);
                    mFavoriteRecyclerView.setAdapter(mFavoriteAdapter);
                }
            }
        }
    }

    @Override
    public void OnItemClick(View v, int position, String type) {
        if ("download".equals(type)) {
            DownloadFolderJob folderJob;
            if (mDownloadData != null && mDownloadData.valueAt(position) instanceof DownloadFolderJob) {
                folderJob = mDownloadData.valueAt(position);
                if (folderJob.getDownloadJobs().size() == 1) {
                    DownloadJob job = folderJob.getDownloadJobs().valueAt(0);

                    if (job.getProgress() >= 10) {
                        if (DownloadHelper.getAbsolutePath(job.getEntity(), job
                                .getEntity().getPath()) == null
                                || DownloadHelper.getDownloadedFileSize(
                                job.getEntity(), job.getEntity().getPath()) == 0) {
                            Toast.makeText(getActivity(),
                                    R.string.file_has_been_removed, Toast.LENGTH_SHORT)
                                    .show();
                            return;
                        }
                        String filePath = DownloadHelper.getPath(
                                job.getEntity(), job.getEntity().getPath());
                        if (!TextUtils.isEmpty(filePath)) {
                            File file = new File(filePath);
                            if (file.exists()) {
                                Map<String, String> dataMap = BigDataApi.createDataMap("0", "moduleId=download", "0", "-", job.getEntity().getMid(), "-");
                                dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_MY);
                                dataMap.put("pid", job.getEntity().getMid());
                                if (mLoginSp != null) {
                                    dataMap.put("uid", mLoginSp.getString(LoginActivity.UID, ""));
                                }
                                dataMap.put("ilu", mLoginSp == null || TextUtils.isEmpty(mLoginSp.getString(LoginActivity.UID, "")) ? "0" : "1");
                                BigDataApi.bigDataCommonReport(dataMap, getActivity());

                                mDownloadManager.playVideo(job);
                                mDownloadManager.notifyObservers();
                            } else {
                                ToastUtil.showShortToast(getActivity(),
                                        R.string.filedeletetip);
                            }
                        } else {
                            ToastUtil.showShortToast(getActivity(),
                                    R.string.filedeletetip);
                        }
                    } else {
                        Toast.makeText(getActivity(), R.string.download_can_play_rate,
                                Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Map<String, String> dataMap = BigDataApi.createDataMap("0", "moduleId=download", "0", "-", folderJob.getMediaId(), "-");
                    dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_MY);
                    dataMap.put("pid", folderJob.getMediaId());
                    if (mLoginSp != null) {
                        dataMap.put("uid", mLoginSp.getString(LoginActivity.UID, ""));
                    }
                    dataMap.put("ilu", mLoginSp == null || TextUtils.isEmpty(mLoginSp.getString(LoginActivity.UID, "")) ? "0" : "1");
                    BigDataApi.bigDataCommonReport(dataMap, getActivity());

                    Intent intent = new Intent(getActivity(), DownloadJobActivity.class);
                    intent.putExtra("index", position);
                    intent.putExtra("mediaName", folderJob.getMediaName());
                    intent.putExtra("mediaId", folderJob.getMediaId());
                    startActivity(intent);
                }
            }
        } else if ("history".equals(type)) {
            PlayRecord currplayRecord = null;
            if (playRecordList != null) {
                currplayRecord = playRecordList.get(position);
            }
            if (null != currplayRecord) {
                Map<String, String> dataMap = BigDataApi.createDataMap("0", "moduleId=history","0","-",currplayRecord.getAid(),"-");
                dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_HISTORY);
                dataMap.put("pid", currplayRecord.getAid());
                if (mLoginSp != null) {
                    dataMap.put("uid", mLoginSp.getString(LoginActivity.UID, ""));
                }
                dataMap.put("ilu", mLoginSp == null || TextUtils.isEmpty(mLoginSp.getString(LoginActivity.UID, "")) ? "0" : "1");
                BigDataApi.bigDataCommonReport(dataMap, getActivity());
                RealDataApi.RealDataClickReport("","",currplayRecord.getAid(),"","");
                String url = currplayRecord.getUrl();
                if (isLocalUrl(url)) {
                    String fileUrl = url.replace(PREFIX, "").trim();
                    File localFile = new File(fileUrl);
                    //判断当前的URL是否是本地的URL
                    if (null != localFile && localFile.exists()) {
                        PlayData playData = setLocalData(url, currplayRecord);
                        jumpToPlayActivity(playData);
                    } else {

                    }
                } else {
                    onLineLogic(currplayRecord);
                }
            }
        } else if ("favorite".equals(type)) {
            Favorite favorite = favoriteList.get(position);
            favorite.setUpdate();
            favoriteDao.update(favorite);
            Map<String, String> dataMap = BigDataApi.createDataMap("0", "moduleId=favorite","0","-",favorite.getAid(),"-");
            dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_COLLECT);
            dataMap.put("pid", favorite.getAid());
            if (mLoginSp != null) {
                dataMap.put("uid", mLoginSp.getString(LoginActivity.UID, ""));
            }
            dataMap.put("ilu", mLoginSp == null || TextUtils.isEmpty(mLoginSp.getString(LoginActivity.UID, "")) ? "0" : "1");
            BigDataApi.bigDataCommonReport(dataMap, getActivity());
            RealDataApi.RealDataClickReport("","",favorite.getAid(),"","");
            VideoDetailActivity.launch(getActivity(), favorite.getAid(), favorite.getVt(), favorite.getName(), favorite.getSrc(), "", "", "0","","");
        }
    }

    @Override
    public void requestSuccess(int updateId, Object data, String name) {
        if(name.equals(MoviesHttpApi.GET_FAVORITE_DATA)) { //收藏列表
            favoriteList = ((CollectionListBean) data).getCollectionList();
            if (favoriteList == null || favoriteList.size() == 0) {
                mFavoriteRecyclerView.setVisibility(View.GONE);
            } else {
                mFavoriteRecyclerView.setVisibility(View.VISIBLE);
                if (mFavoriteAdapter != null) {
                    mFavoriteAdapter.setDatas(favoriteList);
                    mFavoriteAdapter.notifyDataSetChanged();
                } else {
                    mFavoriteAdapter = new FavoriteGalleryAdapter(getActivity(), favoriteList);
                    mFavoriteAdapter.setOnItemClickListnener(MyFragment.this);
                    mFavoriteRecyclerView.setAdapter(mFavoriteAdapter);
                }
            }
        } else if (name.equals(MoviesHttpApi.USER_PLAY_LIST)) {
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                }
//            }, 100);
            playRecordList = ((PlayRecordList)data).getPlayRecordList();
            if (playRecordList == null || playRecordList.size() == 0) {
                mHistoryRecyclerView.setVisibility(View.GONE);
            } else {
                mHistoryRecyclerView.setVisibility(View.VISIBLE);
                if (mHistoryAdapter != null) {
                    mHistoryAdapter.setDatas(playRecordList);
                    mHistoryAdapter.notifyDataSetChanged();
                } else {
                    mHistoryAdapter = new HistoryGalleryAdapter(getActivity(), playRecordList);
                    mHistoryAdapter.setOnItemClickListnener(MyFragment.this);
                    mHistoryRecyclerView.setAdapter(mHistoryAdapter);
                    mHistoryAdapter.notifyDataSetChanged();
                }
            }
        }

    }

    @Override
    public void requestFail(String name) {

    }

    @Override
    public void netError(String name) {

    }

    @Override
    public void onDownloadChanged(DownloadManager manager) {
        if (MoviesConstant.isRefreshMyFragment) {
            updateDownloadRecord();
            updateFavoriteRecord();
            updateHistoryRecord();
            MoviesConstant.isRefreshMyFragment = false;
        }
    }
    @Override
    public void onDownloadEnd(DownloadManager manager) {
        if (MoviesConstant.isRefreshMyFragment) {
            updateDownloadRecord();
            updateFavoriteRecord();
            updateHistoryRecord();
            MoviesConstant.isRefreshMyFragment = false;
        }
    }

    private boolean isLocalUrl(String url) {
        String prefix = "file:///";
        return !TextUtils.isEmpty(url) && url.startsWith(prefix);
    }

    private PlayData setLocalData(String url, PlayRecord currplayRecord) {
        //设置本地视频播放的相关数据
        ArrayList<String> Url = new ArrayList<String>();
        Url.add(url);
        LocalVideoEpisode localVideoEpisode = new LocalVideoEpisode();
        localVideoEpisode.setAid(currplayRecord.getAid());
        localVideoEpisode.setPorder(currplayRecord.getPorder());
        localVideoEpisode.setName(currplayRecord.getName());
        localVideoEpisode.setVt(currplayRecord.getVt());
        localVideoEpisode.setPlay_url(Url);
        ArrayList<LocalVideoEpisode> localVideoEpisodeList = new ArrayList<LocalVideoEpisode>(1);
        localVideoEpisodeList.add(localVideoEpisode);
        PlayData playData = new PlayData();
        //设置播放的是本地的文件
        playData.setIsLocalVideo(true);
        playData.setmLocalDataLists(localVideoEpisodeList);
        playData.setPorder(currplayRecord.getPorder());//知道播的是哪一集播放器
        playData.setAid(currplayRecord.getPorder());
        playData.setmPlayRecord(currplayRecord);

        return playData;
    }
    private void jumpToPlayActivity(PlayData playData) {
        Intent intent = new Intent(getActivity(), PlayActivitySelfOwn.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(Utils.PLAY_DATA, playData);
        intent.putExtras(bundle);
        getActivity().startActivity(intent);
    }
    private void onLineLogic(PlayRecord record) {
        VideoDetailActivity.launch(getActivity(), record.getAid(),
                record.getVt(), record.getName(), "", "", "", record.getPorder(),"","");
//        LogUtils.i("playrecord", "请求播放源的列表");
//        if (!requestVideoDataTask.isCancelled()) {
//            requestVideoDataTask.cancel();
//        }
//        requestVideoDataTask.start();

    }

    public void updateDownloadRecord() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mDownloadData = mDownloadManager.getProvider().getFolderJobs();
                if (mDownloadData.size() == 0) {
                    mDownloadRecyclerView.setVisibility(View.GONE);
                } else {
                    mDownloadRecyclerView.setVisibility(View.VISIBLE);
                    if (mDownloadAdapter != null) {
                        mDownloadAdapter.setDatas(mDownloadData);
                        mDownloadAdapter.notifyDataSetChanged();
                    } else {
                        mDownloadAdapter = new GalleryAdapter(getActivity(), mDownloadData);
                        mDownloadAdapter.setOnItemClickListnener(MyFragment.this);
                        mDownloadRecyclerView.setAdapter(mDownloadAdapter);
                    }
                }
            }
        }, 200);
    }

    public void updateHistoryRecord() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                    RequestUserPlayRecordsTask task = new RequestUserPlayRecordsTask(getActivity(), 0, 20);
                    task.setRequestListener(MyFragment.this);
                    task.start();
                } else {
                    List<String> noPosterRecordList = new PlayRecordDao(getActivity()).getNoPosterAidList();
                    if(noPosterRecordList != null && noPosterRecordList.size() > 0){
                        new RequestAlbumInfoTask(getActivity(), noPosterRecordList, "record").start();
                    }
                    playRecordList = new PlayRecordDao(getActivity()).getLocalAll();
                    if (playRecordList.size() == 0) {
                        mHistoryRecyclerView.setVisibility(View.GONE);
                    } else {
                        mHistoryRecyclerView.setVisibility(View.VISIBLE);
                        if (mHistoryAdapter != null) {
                            mHistoryAdapter.setDatas(playRecordList);
                            mHistoryAdapter.notifyDataSetChanged();
                        } else {
                            mHistoryAdapter = new HistoryGalleryAdapter(getActivity(), playRecordList);
                            mHistoryAdapter.setOnItemClickListnener(MyFragment.this);
                            mHistoryRecyclerView.setAdapter(mHistoryAdapter);
                        }
                    }
                }
            }
        }, 200);
    }

    public void updateFavoriteRecord() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!"".equals(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                    mRequestGetFavoriteListTask = new RequestGetFavoriteListTask(getActivity(), 0, LIMIT);
                    mRequestGetFavoriteListTask.setRequestListener(MyFragment.this);
                    mRequestGetFavoriteListTask.start();
                } else {
                    List<String> noPosterFavoriteList = favoriteDao.getNoPosterAidList();
                    if(noPosterFavoriteList != null && noPosterFavoriteList.size() > 0){
                        new RequestAlbumInfoTask(getActivity(), noPosterFavoriteList, "favorite").start();
                    }
                    favoriteList=favoriteDao.getAll();
                    if (favoriteList.size() == 0) {
                        mFavoriteRecyclerView.setVisibility(View.GONE);
                    } else {
                        mFavoriteRecyclerView.setVisibility(View.VISIBLE);
                        if (mFavoriteAdapter != null) {
                            mFavoriteAdapter.setDatas(favoriteList);
                            mFavoriteAdapter.notifyDataSetChanged();
                        } else {
                            mFavoriteAdapter = new FavoriteGalleryAdapter(getActivity(), favoriteList);
                            mFavoriteAdapter.setOnItemClickListnener(MyFragment.this);
                            mFavoriteRecyclerView.setAdapter(mFavoriteAdapter);
                        }
                    }
                }
            }
        }, 200);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.menu_upgrade:
                if(!UpdateManager.isUpdating()) {
                    new UpdateManager(getActivity()).startCheck();
                }
                else {
                    UIs.showToast("正在下载更新");
                }
                break;
            case R.id.menu_law:
                Intent lawIntent = new Intent();
                JumpData jumpData = new JumpData();
                Bundle jumpbundle = new Bundle();
                jumpData.setPlayUrl(IdUtils.PRIVACY_LINK);
                jumpData.setName(getString(R.string.law_clause));
                lawIntent.setClass(getActivity(), CommonWebViewActivity.class);
                jumpbundle.putSerializable(Utils.CHANNEL_DTAT, jumpData);
                lawIntent.putExtras(jumpbundle);
                lawIntent.putExtra("id", R.drawable.law_clause);
                getActivity().startActivity(lawIntent);
                break;
            case R.id.click_to_login_rl:
                if(TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))){
                    UmengEventPoster.doEventPost(UmengEventPoster.CLICK_TO_LOGIN);
                    LoginDataRecord loginDataRecord = MyDataRecordCreater.build(LoginDataRecord.class);
                    loginDataRecord.setCur_url("page_uc");
                    loginDataRecord.setAcode("0");
                    loginDataRecord.setAction("login_btn");
                    RealmDaoManager.addMyDataRecord(loginDataRecord);
                    LoginActivity.launch(getActivity(), "page_uc");
                }else{
                    UmengEventPoster.doEventPost(UmengEventPoster.CLICK_USER_INFO);
                    Intent intent = new Intent(getActivity(), UserMessageActivity.class);
                    intent.putExtra("headerIcon", headerIcon);
                    intent.putExtra("userName", userName);
                    intent.putExtra("userSex", userSex);
                    startActivity(intent);
                }
                break;
            case R.id.rl_download_manager:
                Intent intent = new Intent(getActivity(),
                        DownloadActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_play_history:
                PlayHistoryActivity.launch(getActivity());
                break;
            case R.id.menu_favourites:
                FavoriteActivity.launch(getActivity());
                break;
            case R.id.menu_feedback:
                //如果发生错误，请查看logcat日志
                FeedbackAPI.openFeedbackActivity(getActivity());
                break;
            case R.id.menu_setting:
                SettingActivity.launch(getActivity());
                break;
        }
    }

    @Override
    public void onResume() {
        if(TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))){
//			userHeaderIv.setBackgroundResource(R.drawable.login_icon);
            mHeadImageView.setImageResource(R.drawable.login_icon);
            mUnLoginHeadTextView.setText(getResources().getString(R.string.click_to_login));
            mUnLoginHeadTextView.setVisibility(View.VISIBLE);
            mLoginTextViewDescription.setText(getResources().getString(R.string.login_description));
            mLoginTextViewDescription.setVisibility(View.VISIBLE);
            mLoginHeadTextView.setVisibility(View.GONE);
            loginArrowIamge.setVisibility(View.GONE);
        } else {
            if(!TextUtils.isEmpty(headerIcon) && !TextUtils.isEmpty(userName)){
                ImageLoader.getInstance().displayImage(headerIcon, mHeadImageView);
                loginArrowIamge.setVisibility(View.VISIBLE);
                mUnLoginHeadTextView.setText(userName);
                mLoginTextViewDescription.setText("UID: " + mLoginSp.getString(LoginActivity.UID, ""));
            }
            new RequestUserMessageTask(getActivity(), mLoginSp.getString(LoginActivity.TOKEN, "")).start();
        }
        mDownloadManager.registerDownloadObserver(this);
        if (MoviesConstant.isRefreshMyFragment) {
            updateDownloadRecord();
            updateFavoriteRecord();
            updateHistoryRecord();
            MoviesConstant.isRefreshMyFragment = false;
        }
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
        } else {
            if (MoviesConstant.isRefreshMyFragment) {
                updateDownloadRecord();
                updateFavoriteRecord();
                updateHistoryRecord();
                MoviesConstant.isRefreshMyFragment = false;
            }
        }
    }

    @Override
    public void onPause() {
        mDownloadManager.deregisterDownloadObserver(this);
        super.onPause();
    }


    public class RequestUserMessageTask extends MoviesHttpAsyncTask<UserMessageBean> {

        private String token;

        @Override
        public void netNull() {
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
        }

        public RequestUserMessageTask(Context context, String token) {
            super(context);
            this.token = token;
        }

        @Override
        public LVideoDataHull<UserMessageBean> doInBackground() {
            LVideoDataHull<UserMessageBean> ret = MoviesHttpApi.userMessageRequest(
                    new UserMessageParser(), token);
            return ret;
        }

        @Override
        public void onPostExecute(int updateId, UserMessageBean result) {
            mUserMessage = result;
            if(mUserMessage != null){
                headerIcon = mUserMessage.getImg_url();
                userName = mUserMessage.getNick_name();
                userSex = mUserMessage.getSex();
                SharedPreferences.Editor editor = mLoginSp.edit();
                editor.putString(INFOIMAGEURL, headerIcon);
                editor.putString(INFONICKNAME, userName);
                editor.putString(INFOGENDER, userSex);
                editor.commit();
                if(!TextUtils.isEmpty(headerIcon) && !TextUtils.isEmpty(userName)){
                    ImageLoader.getInstance().displayImage(headerIcon, mHeadImageView);
                    loginArrowIamge.setVisibility(View.VISIBLE);
                    mUnLoginHeadTextView.setText(userName);
                    mLoginTextViewDescription.setText("UID: " + mLoginSp.getString(LoginActivity.UID, ""));
                }
            }
        }
    }

    public void setRedPop(boolean isShow){
        if(null != collectRedPop){
            if(isShow){
                collectRedPop.setVisibility(View.VISIBLE);
            }
            else{
                collectRedPop.setVisibility(View.GONE);
            }
        }
    }

}
